# -*- encoding: utf-8 -*-

"""
------------------------------------------
@File       : sync_in_coroutine.py
@Author     : maixiaochai
@Email      : maixiaochai@outlook.com
@CreatedOn  : 2021/9/17 15:36
------------------------------------------
    处理在协程中的同步函数问题
"""
import asyncio
import threading
import time
import os


def ping(url):
    print("阻塞函数开始运行")
    time.sleep(2)
    os.system(f"ping {url}")
    print("阻塞函数运行结束")


async def async_func1():
    print("Suspending func1")
    await asyncio.sleep(1)
    print(f"func: func1", threading.currentThread())
    print("Resuming func1")

    return "func1"


async def async_func2():
    print("Suspending func2")
    await asyncio.sleep(1)
    print(f"func: func1", threading.currentThread())
    print("Resuming func2")

    return "func2"


# ================================[ 单个协程任务的运行 ]================================
if __name__ == '__main__':
    """
        In main thread:  <_MainThread(MainThread, started 16952)>
        Suspending func1
        func: func1 <_MainThread(MainThread, started 16952)>
        Resuming func1
        task result is:  func1
        
    执行过程：
        使用 loop.create_task()方法创建一个 task对象，task是 Futures的子类，
        当调用 loop.run_until_complete()以后，协程跑完以后，通过 task.result()获取协程函数的返回结果
    """
    print("In main thread: ", threading.currentThread())
    loop = asyncio.get_event_loop()
    task = loop.create_task(async_func1())
    loop.run_until_complete(task)
    print("task result is: ", task.result())
